package ds.factcom.model;

import java.util.List;
import java.util.Observable;

import ds.factcom.domain.product.Product;
import ds.factcom.exception.ExistDomainException;
import ds.factcom.exception.IsProductInInvoicesException;
import ds.factcom.exception.NotExistDomainException;
import ds.factcom.repository.ProductRepository;

/**
 * 
 * @author Javier De Luca, Maximiliano Herrera, Matias Samblancat
 *
 */

public class ProductModel extends Observable{
	
	private Product product;
	
	//Constructor

	public ProductModel(){}

	public void delete(String description) throws NotExistDomainException, IsProductInInvoicesException {
		this.findByDescription(description);
		this.isProductInInvoices();
		ProductRepository.getInstance().delete(this.product);
	}

	private void isProductInInvoices() throws IsProductInInvoicesException {
		if (!(this.product.getInvoices().isEmpty())){
			throw new IsProductInInvoicesException();
		}
	}

	public void modify(Float price){
		this.product.setPrice(price);
		this.setChanged();
		this.notifyObservers(Message.PRODUCT_MODIFIED);
	}

	public void insert(String description, Float price) throws ExistDomainException{
		try {
			this.findByDescription(description);
			if (this.product!=null){
				throw new ExistDomainException(description);
			}
		} catch (NotExistDomainException e) {
			Product product = new Product(description, price);
			ProductRepository.getInstance().insert(product);
			this.setChanged();
			this.notifyObservers(Message.PRODUCT_SAVED);
		}
	}
	
	public void findByDescription(String description) throws NotExistDomainException {
		this.product =  ProductRepository.getInstance().findByDescription(description);
	}

	public String getPrice() {
		return String.valueOf(this.product.getPrice());
	}

	public boolean existProduct() {
		if(product != null ){
			return true;
		}
		return false;
	}
	
	public Product getProduct() {
		return product;
	}
	
	public List<Product> getProductList(){
		return ProductRepository.getInstance().getProductList();
	}

	public void setProduct(Product product) {
		this.product = product;
	}
}